<?php
declare (strict_types = 1);

namespace app\middleware;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\SignatureInvalidException;

class JwtAuth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $token = $request->header('Authorization');
        
        if (!$token) {
            return json([
                'code' => 401,
                'message' => '未提供认证令牌'
            ]);
        }
        
        // 移除Bearer前缀
        $token = str_replace('Bearer ', '', $token);
        
        try {
            $decoded = JWT::decode($token, new Key(config('jwt.secret'), config('jwt.algo')));
            $request->user = (array) $decoded;
        } catch (ExpiredException $e) {
            return json([
                'code' => 401,
                'message' => '认证令牌已过期'
            ]);
        } catch (SignatureInvalidException $e) {
            return json([
                'code' => 401,
                'message' => '认证令牌无效'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 401,
                'message' => '认证失败'
            ]);
        }
        
        return $next($request);
    }
} 